<template>
	<!-- 主弹框 -->
	<view class="notice-modal" v-if="visible" @touchmove.stop.prevent>
		<view class="modal-mask" @click="close"></view>
		<view class="modal-content">
			<view class="modal-header">
				<text class="modal-title">创建直播预告</text>
				<button class="create-btn" @click="handleCreate">创建</button>
			</view>

			<view class="form-content">
				<!-- 直播标题 -->
				<view class="form-title">
					<view style="display: flex;">
						<text class="item-label">直播标题</text>
						<text style="color: red;">*</text>
					</view>

					<textarea v-model="title" class="intro-textarea" placeholder="请输入直播标题" maxlength="15"
						style="height: 100rpx;margin-bottom: 40rpx;"></textarea>
					<text class="word-count">{{ title.length }}/15</text>
				</view>

				<!-- 开播时间 -->
				<view class="form-item" @click="openTimePicker">
					<view style="display: flex;">
						<text class="item-label">开播时间</text>
						<text style="color: red;">*</text>
					</view>

					<view class="item-value">
						<text class="time-text" :class="{placeholder: !selectedTime}">
							{{ selectedTime || '请选择' }}
						</text>
						<uni-icons type="right" size="20"></uni-icons>
					</view>
				</view>

				<!-- 预告封面 -->
				<view class="form-item">
					<text class="item-label">预告封面</text>
					<view class="cover-upload" @click="chooseCover">
						<image v-if="coverImage" :src="coverImage" class="cover-image" mode="aspectFill"></image>
						<view v-else class="upload-placeholder">
							<text class="plus-icon">+</text>
						</view>
					</view>
				</view>

				<!-- 直播介绍 -->
				<view class="form-item">
					<text class="item-label">直播介绍</text>
					<textarea v-model="introduction" class="intro-textarea" placeholder="直播介绍可以更好的帮助观众了解您的直播内容"
						maxlength="100"></textarea>
					<text class="word-count">{{ introduction.length }}/100</text>
				</view>
			</view>
		</view>

		<!-- 时间选择器弹框 -->
		<view v-if="showTimePicker" class="time-picker-modal">
			<view class="picker-mask" @click="cancelTimePicker"></view>
			<view class="picker-content">
				<view class="picker-header">
					<text class="picker-title">选择开播时间</text>
					<text class="picker-tip">请选择1小时后-7天内的开播时间</text>
				</view>
				<picker-view :value="pickerValue" @change="handleTimeChange" class="time-picker"
					indicator-style="height: 80rpx;">
					<picker-view-column>
						<view v-for="(item,index) in days" :key="index" class="picker-item">{{item}}</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(item,index) in hours" :key="index" class="picker-item">{{item}}时</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(item,index) in minutes" :key="index" class="picker-item">{{item}}分</view>
					</picker-view-column>
				</picker-view>
				<view class="picker-buttons">
					<button class="picker-btn cancel" @click="cancelTimePicker" hover-class="none">取消</button>
					<button class="picker-btn confirm" @click.stop="confirmTimePicker" hover-class="none">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'

	export default {
		components: {
			uniIcons
		},
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			// 新增：接收可能传入的初始时间数据
			initialData: {
				type: Object,
				default: () => ({})
			}
		},
		data() {
			const now = new Date()
			// 计算最小可选时间（当前时间+1小时）
			const minTime = new Date(now.getTime() + 60 * 60 * 1000)
			// 计算最大可选时间（当前时间+7天）
			const maxTime = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)

			return {
				showTimePicker: false,
				selectedTime: '', // 存储YYYY-MM-DD HH:mm格式字符串
				selectedTimeObj: null, // 存储Date对象
				coverImage: '',
				introduction: '',
				title: '',
				// 时间选择器相关数据
				minTime, // 最小可选时间
				maxTime, // 最大可选时间
				pickerValue: this.getInitialPickerValue(minTime), // 初始化时间选择器值
				days: this.generateDaysArray(), // 生成YYYY-MM-DD格式的日期数组
				hours: Array.from({
					length: 24
				}, (_, i) => i),
				minutes: Array.from({
					length: 60
				}, (_, i) => i),
				tempTime: null
			}
		},
		watch: {
			// 监听初始数据变化
			initialData: {
				immediate: true,
				handler(newVal) {
					if (newVal.time) {
						this.selectedTime = newVal.time
						this.selectedTimeObj = this.parseTimeString(newVal.time)
						this.title = newVal.title || ''
						this.introduction = newVal.introduction || ''
						this.coverImage = newVal.cover || ''
					}
				}
			}
		},
		methods: {
			// 解析YYYY-MM-DD HH:mm格式字符串为Date对象
			parseTimeString(timeStr) {
				if (!timeStr) return null
				const [datePart, timePart] = timeStr.split(' ')
				const [year, month, day] = datePart.split('-').map(Number)
				const [hours, minutes] = timePart.split(':').map(Number)
				return new Date(year, month - 1, day, hours, minutes)
			},

			// 生成初始时间选择器值
			getInitialPickerValue(minTime) {
				const now = new Date()
				// 计算日期差（0-6）
				const dayDiff = Math.floor((minTime - now) / (24 * 60 * 60 * 1000))
				return [
					Math.max(0, dayDiff), // 确保日期索引有效
					minTime.getHours(),
					minTime.getMinutes()
				]
			},

			// 生成可选的日期数组（YYYY-MM-DD格式）
			generateDaysArray() {
				const days = []
				const now = new Date()

				for (let i = 0; i < 7; i++) {
					const date = new Date(now)
					date.setDate(now.getDate() + i)
					// 格式化日期为YYYY-MM-DD
					const year = date.getFullYear()
					const month = this.addZero(date.getMonth() + 1)
					const day = this.addZero(date.getDate())
					days.push(`${year}-${month}-${day}`)
				}
				return days
			},

			close() {
				this.$emit('close')
			},

			// 获取选择的时间对象
			getSelectedTimeObject(pickerValue = this.pickerValue) {
				const now = new Date()
				const dayIndex = pickerValue[0]
				const hour = this.hours[pickerValue[1]]
				const minute = this.minutes[pickerValue[2]]

				// 创建新的日期对象
				const selectedDate = new Date(now)
				selectedDate.setDate(now.getDate() + dayIndex)
				selectedDate.setHours(hour, minute, 0, 0)

				return selectedDate
			},

			// 格式化显示时间（X月X日 XX:XX）
			formatDisplayTime(timeStr) {
				if (!timeStr) return ''
				try {
					const [datePart, timePart] = timeStr.split(' ')
					const [year, month, day] = datePart.split('-')
					const [hour, minute] = timePart.split(':')
					return `${parseInt(month)}月${parseInt(day)}日 ${hour}:${minute}`
				} catch (e) {
					console.error('时间格式化错误:', e)
					return timeStr
				}
			},

			handleCreate() {
				// 表单验证
				if (!this.title) {
					uni.showToast({
						title: '请输入直播标题',
						icon: 'none'
					})
					return
				}

				if (!this.selectedTimeObj) {
					uni.showToast({
						title: '请选择开播时间',
						icon: 'none'
					})
					return
				}

				const now = new Date()
				const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000)

				if (this.selectedTimeObj.getTime() < oneHourLater.getTime()) {
					uni.showToast({
						title: '只能预告1小时后的直播哦',
						icon: 'none'
					})
					return
				}

				if (this.selectedTimeObj.getTime() > this.maxTime.getTime()) {
					uni.showToast({
						title: '最多只能预告7天内的直播',
						icon: 'none'
					})
					return
				}

				this.$emit('create', {
					time: this.selectedTime, // 传递YYYY-MM-DD HH:mm格式字符串
					timeObj: this.selectedTimeObj, // 传递Date对象
					cover: this.coverImage,
					title: this.title,
					introduction: this.introduction
				})
				this.resetForm()
				this.close()
			},

			resetForm() {
				this.selectedTime = ''
				this.selectedTimeObj = null
				this.coverImage = ''
				this.title = ''
				this.introduction = ''
				const minTime = new Date(new Date().getTime() + 60 * 60 * 1000)
				this.pickerValue = this.getInitialPickerValue(minTime)
			},

			openTimePicker() {
				this.showTimePicker = true
				// 如果已有选择的时间，初始化pickerValue
				if (this.selectedTimeObj) {
					const now = new Date()
					const diffDays = Math.floor((this.selectedTimeObj - now) / (1000 * 60 * 60 * 24))
					const hours = this.selectedTimeObj.getHours()
					const minutes = this.selectedTimeObj.getMinutes()

					this.pickerValue = [
						Math.min(Math.max(diffDays, 0), 6), // 确保在0-6范围内
						hours,
						minutes
					]
				}
			},

			cancelTimePicker() {
				this.showTimePicker = false
				this.tempTime = null
			},

			confirmTimePicker() {
				const selectedTimeObj = this.getSelectedTimeObject()
				const now = new Date()
				const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000)

				// 验证时间范围
				if (selectedTimeObj.getTime() < oneHourLater.getTime()) {
					uni.showToast({
						title: '只能预告1小时后的直播哦',
						icon: 'none'
					})
					return
				}

				if (selectedTimeObj.getTime() > this.maxTime.getTime()) {
					uni.showToast({
						title: '最多只能预告7天内的直播',
						icon: 'none'
					})
					return
				}

				this.selectedTimeObj = selectedTimeObj
				this.selectedTime = this.formatPickerTime() // 格式化为YYYY-MM-DD HH:mm
				this.showTimePicker = false
				this.tempTime = null
			},

			handleTimeChange(e) {
				this.pickerValue = e.detail.value
				this.tempTime = this.formatPickerTime()
			},

			// 格式化时间为YYYY-MM-DD HH:mm
			formatPickerTime() {
				const dayStr = this.days[this.pickerValue[0]] // 已为YYYY-MM-DD格式
				const hour = this.addZero(this.hours[this.pickerValue[1]])
				const minute = this.addZero(this.minutes[this.pickerValue[2]])
				return `${dayStr} ${hour}:${minute}`
			},

			// 数字补零
			addZero(num) {
				return num < 10 ? `0${num}` : num
			},

			chooseCover() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album'],
					success: (res) => {
						this.coverImage = res.tempFilePaths[0]
					},
					fail: (err) => {
						console.error('选择封面失败:', err)
						uni.showToast({
							title: '选择封面失败',
							icon: 'none'
						})
					}
				})
			}
		}
	}
</script>
<style lang="scss">
	.notice-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 10000;

		.modal-mask {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
		}

		.modal-content {
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;
			background-color: #fff;
			border-radius: 24rpx 24rpx 0 0;
			max-height: 80vh;
			overflow-y: auto;
		}

		.modal-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #f0f0f0;

			.modal-title {
				font-size: 34rpx;
				font-weight: bold;
				color: #333;
			}

			.create-btn {
				background: none;
				border: none;
				color: #55aaff;
				font-size: 32rpx;
				padding: 0;
				margin: 0;
				line-height: 1;

				&::after {
					border: none;
				}
			}
		}

		.form-content {
			padding: 30rpx;
		}

		.form-item {
			margin-bottom: 40rpx;

			.item-label {
				display: block;
				font-size: 30rpx;
				color: #333;
				margin-bottom: 20rpx;
				font-weight: 500;
			}

			.item-value {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #f0f0f0;

				.time-text {
					font-size: 28rpx;
					color: #333;

					&.placeholder {
						color: #999;
					}
				}
			}

			.intro-textarea {
				width: 100%;
				height: 200rpx;
				background-color: #f7f7f7;
				border-radius: 8rpx;
				padding: 20rpx;
				box-sizing: border-box;
				font-size: 28rpx;
				color: #333;
			}

			.cover-upload {
				width: 200rpx;
				height: 200rpx;
				background-color: #f7f7f7;
				border-radius: 8rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.cover-image {
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
				}

				.upload-placeholder {
					text-align: center;

					.plus-icon {
						font-size: 60rpx;
						color: #ccc;
						line-height: 1;
					}
				}
			}

			.form-title {
				margin-bottom: 40rpx;
			}

			.word-count {
				display: block;
				text-align: right;
				font-size: 24rpx;
				color: #999;
				margin-top: 10rpx;
			}
		}

		.time-picker-modal {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			z-index: 1001;

			.picker-mask {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background-color: rgba(0, 0, 0, 0.5);
			}



			.picker-content {
				position: absolute;
				bottom: 0;
				left: 0;
				width: 100%;
				background-color: #fff;
				border-radius: 24rpx 24rpx 0 0;
				padding: 20rpx;
				box-sizing: border-box;
				z-index: 1002;
			}

			.picker-header {
				text-align: center;
				padding: 20rpx 0;

				.picker-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}

				.picker-tip {
					font-size: 24rpx;
					color: #999;
					display: block;
					margin-top: 10rpx;
				}
			}

			.time-picker {
				height: 400rpx;
			}

			.picker-item {
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				font-size: 28rpx;
				color: #333;
			}

			.picker-buttons {
				display: flex;
				justify-content: space-between;
				margin-top: 20rpx;
				z-index: 1003;

				.picker-btn {
					flex: 1;
					height: 80rpx;
					line-height: 80rpx;
					text-align: center;
					font-size: 30rpx;
					background: none;
					border: none;
					padding: 0;
					margin: 0;
					position: relative;
					z-index: 1004;
				}

				.picker-btn::after {
					border: none;
				}

				.picker-btn.cancel {
					color: #999;
				}

				.picker-btn.confirm {
					color: #55aaff;
				}
			}
		}
	}
</style>